package com.appbee.cm.client.nav.ui;

import javax.inject.Inject;

import com.appbee.cm.client.nav.presenter.NavAdminPresenter;
import com.appbee.cm.client.nav.presenter.NavItemWrap;
import com.appbee.cm.client.nav.text.NavText;
import com.appbee.core.client.templates.CommonTemplates;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.PopupPanel;

public class NavCell extends AbstractCell<NavItemWrap>
{
	private final CommonTemplates templates;
	private final PopupPanel popupPanel = new PopupPanel(true);
	private NavAdminPresenter presenter;
	private NavItemWrap value;
	private final NavText navText;
	private final INavAdminStyle style;

	@Inject
	public NavCell(	CommonTemplates templates,
					NavText navText,
					INavAdminStyle style)
	{
		super("click");
		this.templates = templates;
		this.navText = navText;
		this.style = style;
		MenuBar menuBar = new MenuBar(true);
		menuBar.addItem(navText.newSubpage(), new Command()
		{

			@Override
			public void execute()
			{
				popupPanel.hide();
				presenter.doNew(value);
			}
		});
		menuBar.addItem(navText.deletePage(), new Command()
		{

			@Override
			public void execute()
			{
				popupPanel.hide();
				presenter.doDelete(value);
			}
		});
		popupPanel.setWidget(menuBar);
	}

	public void setPresenter(NavAdminPresenter presenter)
	{
		this.presenter = presenter;
	}

	@Override
	public void render(	com.google.gwt.cell.client.Cell.Context context,
						NavItemWrap value,
						SafeHtmlBuilder sb)
	{
		sb.appendEscaped(value.getName());
		sb.append(templates.button(	style.itemMenu(),
									"menu",
									navText.menu(),
									navText.menu()));

	}

	@Override
	public void onBrowserEvent(	com.google.gwt.cell.client.Cell.Context context,
								Element parent,
								NavItemWrap value,
								NativeEvent event,
								ValueUpdater<NavItemWrap> valueUpdater)
	{
		this.value = value;
		Element el = event.getEventTarget().cast();
		if ("BUTTON".equals(el.getTagName()))
		{
			popupPanel.setPopupPosition(el.getAbsoluteLeft(),
										el.getAbsoluteBottom());
			popupPanel.show();
		}
	}

}
